package com.admin.action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.admin.bean.CompanyBean;
import com.admin.bean.DownloadLogBean;
import com.admin.bean.MobileUserBean;
import com.admin.cache.EhCacheManager;
import com.admin.dao.ConsumeOrderDao;
import com.admin.dao.ProvinceDao;
import com.admin.hessian.ScriptBean;
import com.admin.hessian.ScriptService;
import com.admin.service.BillingService;
import com.admin.service.CompanyService;
import com.admin.service.DownloadLogService;
import com.admin.service.MobileUserService;
import com.admin.util.BaseUtil;
import com.admin.util.PageBean;

@Controller
@RequestMapping("/user")
public class MobileUserAction {

	private static final Logger log = Logger.getLogger(MobileUserAction.class);

	@Autowired
	private MobileUserService mobileUserService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private ProvinceDao provinceDao;
	@Autowired
	private ConsumeOrderDao consumeOrderDao;

	@Autowired
	private ScriptService scriptService;

	@Autowired
	private BillingService billingService;
	
	@Autowired
	private DownloadLogService downloadLogService;

	@RequestMapping()
	public String search(HttpServletRequest request) {
		StringBuffer url = new StringBuffer("?1=1");
		int isp = BaseUtil.stringToInt(request.getParameter("isp"), -1);
		if (isp >= 0) {
			url.append("&isp=" + isp);
		}
		int provinceId = BaseUtil.stringToInt(request.getParameter("provinceId"), -1);
		if (provinceId >= 0) {
			url.append("&provinceId=" + provinceId);
		}
		int sid = BaseUtil.stringToInt(request.getParameter("sid"), -1);
		if (sid >= 0) {
			url.append("&sid=" + sid);
		}
		int userType = BaseUtil.stringToInt(request.getParameter("userType"), -1);
		if (userType >= 0) {
			url.append("&userType=" + userType);
		}
		String telPhone = request.getParameter("telPhone");
		if (StringUtils.isNotEmpty(telPhone)) {
			url.append("&telPhone=" + telPhone);
		}
		int currentPage = BaseUtil.stringToInt(request.getParameter("currentPage"), 1);
		MobileUserBean user = new MobileUserBean();
		user.setIsp(isp);
		user.setProvinceId(provinceId);
		user.setSid(sid);
		user.setUserType(userType);
		user.setTelPhone(telPhone);
		int totalCount = mobileUserService.findCountByCondition(user);
		PageBean<MobileUserBean> pageBean = new PageBean<MobileUserBean>(totalCount, currentPage, 15);
		List<MobileUserBean> userList = mobileUserService.findByCondition(user, pageBean.getStart(), pageBean.getPageSize());
		pageBean.setResult(userList);
		pageBean.setUrl(url.toString());
		request.setAttribute("pageBean", pageBean);
		request.setAttribute("user", user);

		List<CompanyBean> companyList = companyService.findAllList();
		request.setAttribute("companyList", companyList);
		return "userList";
	}

	@RequestMapping("/{userId}")
	public String show(@PathVariable int userId, HttpServletRequest request) {
		MobileUserBean user = mobileUserService.findByUserId(userId);
		request.setAttribute("user", user);
		return "userView";
	}

	@RequestMapping("/update")
	public ModelAndView updateUserType(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int userId = BaseUtil.stringToInt(request.getParameter("userId"));
		int userType = BaseUtil.stringToInt(request.getParameter("userType"));
		int result = mobileUserService.updateUserType(userType, userId);
		response.setContentType("text/html");
		response.getWriter().print(result);
		return null;
	}

	@RequestMapping("/del/{userId}")
	public ModelAndView delTestUser(@PathVariable int userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		int result = mobileUserService.delUser(userId);
		response.setContentType("text/html");
		response.getWriter().print(result);
		return null;
	}

	
	//TODO 短信注册
	@RequestMapping("/phone")
	public ModelAndView insertTelPhone(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
		//log.info("===================进入短信注册===================");
		String nid = request.getParameter("msg");
		String telPhone = request.getParameter("phone");
		//log.info("MSG==>" + nid + "//PHONE==>" + telPhone);
		if (StringUtils.isNotEmpty(nid) && StringUtils.isNotEmpty(telPhone)) {
			String str[] = nid.split("#");
			/*
			 * if(str.length==3){ log.info("进入浏览器短信注册==>"); MobileUserBean user
			 * = mobileUserService.findByTelPhone(telPhone);//根据手机号码查询 String
			 * smsp = str[1]; String ismi = str[2]; if(user==null){
			 * mobileUserService.updateTelPhone(smsp, ismi, telPhone); }else{
			 * user.setSmsp(smsp); user.setIsmi(ismi);
			 * user.setTelPhone(telPhone); if(user.getProvinceId()==0){
			 * user.setProvinceId(provinceDao.getProvinceId(telPhone)); }
			 * mobileUserService.updateUser(user); }
			 * log.info("=================浏览器短信注册结束================="); }else{
			 */
			int sid = BaseUtil.stringToInt(str[1]);
			int cid = BaseUtil.stringToInt(str[2]);
			String smsp = str[3];
			String ismi = str[4];
			String softversion = str[5];
			String cardtype = str[6];
			String midc = "";
			if (str.length == 9) {
				midc = str[7] + "#" + str[8];
			}
			MobileUserBean user = mobileUserService.findByTelPhone(telPhone);// 根据手机号码查询
			if (user == null) {
				//log.info("根据用户手机号查询为空，接下来根据MID查询用户");
				user = mobileUserService.findBySmspAndIsmi(smsp, ismi);
				if (user == null) {
					//log.info("根据MID查询用户为空，则进行新用户注册");
					user = new MobileUserBean();
					user.setSmsp(smsp);
					user.setIsmi(ismi);
					user.setSid(sid);
					user.setCid(cid);
					user.setSoftwareVersion(softversion);
					user.setMidc(midc);
					user.setUserAgent("");
					user.setCardType(cardtype);
					user.setBtAddr("");
					user.setImei("");
					user.setLcdHeight(0);
					user.setLcdWidth(0);
					if ("mobile".equals(cardtype)) {
						user.setIsp(0);
					} else {
						user.setIsp(1);
					}
					user.setUserType(0);
					user.setTelPhone(telPhone);
					user.setRegCount(1);
					int provincdId = getProvinceId(telPhone, smsp);
					user.setProvinceId(provincdId);
					mobileUserService.addUser(user);
				} else if (user.getIsmi().equals(ismi) && user.getSmsp().equals(smsp)) {
					//log.info("根据MID查询用户不为空,userId=" + user.getUserId() + "，覆盖信息");
					user.setSmsp(smsp);
					user.setIsmi(ismi);
					user.setSid(sid);
					user.setCid(cid);
					user.setSoftwareVersion(softversion);
					user.setMidc(midc);
					user.setCardType(cardtype);
					if ("mobile".equals(cardtype)) {
						user.setIsp(0);
					} else {
						user.setIsp(1);
					}
					user.setTelPhone(telPhone);
					user.setRegCount(user.getRegCount() + 1);
					if (user.getProvinceId() == 0) {
						user.setProvinceId(getProvinceId(telPhone, smsp));
					}
					mobileUserService.updateUser(user);
				} else {
					//log.error("出现错误==>");
				}
			} else if (user.getTelPhone().equals(telPhone)) {
				//log.info("已有该手机号码:" + telPhone + "用户基本信息，覆盖信息");
				user.setSmsp(smsp);
				user.setIsmi(ismi);
				user.setSid(sid);
				user.setCid(cid);
				user.setSoftwareVersion(softversion);
				user.setMidc(midc);
				user.setCardType(cardtype);
				if ("mobile".equals(cardtype)) {
					user.setIsp(0);
				} else {
					user.setIsp(1);
				}
				user.setTelPhone(telPhone);
				user.setRegCount(user.getRegCount() + 1);
				user.setProvinceId(getProvinceId(telPhone, smsp));
				mobileUserService.updateUser(user);
			} else {
				//log.error("出现错误==>");
			}
			//log.info("=================开机短信注册结束=================");
			// }
		}
		response.getWriter().print("OK");
		return null;
	}

	private int getProvinceId(String telPhone, String smsp) throws SQLException {
		//log.info("根据手机号码：" + telPhone + "取省份ID");
		int provincdId = provinceDao.getProvinceId(telPhone);
		if (provincdId == 0) {
			//log.info("根据SMSP：" + smsp + "取省份ID");
			provincdId = provinceDao.getProvinceIdBySmsp(smsp);
		}
		//log.info("得到省份ID：" + provincdId);
		return provincdId;
	}

	
	//TODO 联网请求，记录基本信息
	@RequestMapping("/reg")
	public ModelAndView reg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.info("===============进入开机联网请求注册==================");
		int SID = BaseUtil.stringToInt(request.getHeader("SID"));
		int CID = BaseUtil.stringToInt(request.getHeader("CID"));
		String MID = request.getHeader("MID");
		String phone = request.getHeader("PN");
		String Softversion = request.getHeader("Softversion");
		String Useragent = request.getHeader("Useragent");
		String Cardtype = request.getHeader("Cardtype");
		String Btaddr = request.getHeader("Btaddr");
		String IMEI = request.getHeader("IMEI");
		int LCD_H = BaseUtil.stringToInt(request.getHeader("LCD_H"));
		int LCD_W = BaseUtil.stringToInt(request.getHeader("LCD_W"));
		String MIDC = request.getHeader("MIDC");
//		log.info("SID:" + SID);
//		log.info("CID" + CID);
//		log.info("MID:" + MID);
//		log.info("MIDC:" + MIDC);
//		log.info("phone:" + phone);
//		log.info("Softversion:" + Softversion);
//		log.info("Useragent:" + Useragent);
//		log.info("Cardtype:" + Cardtype);
//		log.info("Btaddr:" + Btaddr);
//		log.info("IMEI:" + IMEI);
//		log.info("LCD_H:" + LCD_H);
//		log.info("LCD_W:" + LCD_W);
		String trone = "";
		String command = "";
		String smsp = "";
		String ismi = "";
		boolean flag = true;// 默认已注册
		String str[] = null;
		if (MID != null && !"".equals(MID)) {
			str = MID.split("#");
			smsp = str[0];
			ismi = str.length == 2 ? str[1] : "";
		} else {
			ismi = BaseUtil.genRandomNum(4);
			smsp = "R" + SID + CID + BaseUtil.genRandomNum(5);
			//log.info("产生ISMI：" + ismi + ",SMSP:" + smsp);
			MID = smsp + "#" + ismi;
		}
		if ("mobile".equals(Cardtype)) {
			trone = "106575557760";
		} else {
			trone = "1065505956900007";
		}
		MobileUserBean user = mobileUserService.findBySmspAndIsmi(smsp, ismi);
		if (user == null) {
			log.info("新用户，进行注册");
			user = new MobileUserBean();
			user.setSmsp(smsp);
			user.setIsmi(ismi);
			user.setSid(SID);
			user.setCid(CID);
			user.setSoftwareVersion(Softversion);
			user.setUserAgent(Useragent);
			user.setCardType(Cardtype);
			user.setBtAddr(Btaddr);
			user.setImei(IMEI);
			user.setLcdHeight(LCD_H);
			user.setLcdWidth(LCD_W);
			user.setRegCount(0);
			if ("mobile".equals(Cardtype)) {
				user.setIsp(0);
			} else {
				user.setIsp(1);
			}
			user.setUserType(0);
			user.setProvinceId(getProvinceId(smsp));
			mobileUserService.addUser(user);
			flag = false;
		} else {
			String telPhone = user.getTelPhone();
			if (StringUtils.isNotEmpty(telPhone)) {
				if (smsp.startsWith("R")) {// 随机MID用户
					int count = consumeOrderDao.findCountByUserId(user.getUserId());// 取该用户消费次数
					if (count == 0) {// 没有消费
						int regCount = user.getRegCount();
						if (regCount >= 5) {
							//log.info("该用户是MID随机用户,已经完成注册第二步了，但没有消费过,且已经注册大于5次，不再发生注册短信，手机号码为：" + telPhone);
							response.setHeader("Expires", "PN:" + telPhone);
						} else {
							//log.info("该用户是MID随机用户,已经完成注册第二步了，但没有消费过,且已经注册少于5次，需要从新发生注册短信注册");
							response.setHeader("Expires", "MID:" + MID);
							flag = false;
						}
					} else {// 已经消费过了
						//log.info("该用户已经完成第二步了，并已经消费过了，不需要发短信，手机号码为：" + telPhone);
						response.setHeader("Expires", "PN:" + telPhone);
					}
				} else {// 正常用户
					//log.info("该用户是正常用户，且完成第二步了，不需要发短信，手机号码为：" + telPhone);
					response.setHeader("Expires", "PN:" + telPhone);
				}
			} else {
				//log.info("没有电话号码，需要发短信！");
				flag = false;
			}
		}
		command = "SasasaZeus#" + SID + "#" + CID + "#" + MID + "#" + Softversion + "#" + Cardtype + "#" + MIDC;
		
		log.info("***************************************************");
		int random = RandomUtils.nextInt(1000);
		if(random%5==0) {
			DownloadLogBean logBean = new DownloadLogBean();
			logBean.setCid(CID);
			logBean.setSid(SID);
			logBean.setImsi(ismi);
			logBean.setProvince(user.getProvinceId());
			downloadLogService.insertDwonloadLog(logBean);
		}
		
		
		downXml(response, command, flag, trone, MID, SID, CID);
		//log.info("===============开机联网请求注册结束==================");
		return null;
	}

	private void downXml(HttpServletResponse response, String command, boolean flag, String trone, String MID, int SID, int CID)
			throws IOException {
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		xml.append("<reg>");
		xml.append("<time>" + 32 + "</time>");	//24 * 20
		xml.append("<register>");
		if (flag) {// 表示已经注册了
			xml.append(1);
			xml.append("</register>");
			// if ((SID == 24 && CID == 27) || (SID == 27 && CID == 30) || (SID
			// == 28 && CID == 31)) {
			int feeId = billingService.getFeeIdByCID(CID);
			if (feeId != 0) {
				ScriptBean scriptBean = scriptService.getScript(feeId, MID, 0);
				xml.append(scriptBean == null ? "" : scriptBean.getScriptStr());
			}
			// }
		} else {
			xml.append(0);
			xml.append("</register>");
			xml.append("<info type=\"feeTask\" id=\"subreg\" feeType=\"sms\" feeTimes=\"1\" showType=\"A\" command=\"" + command
					+ "\" trone=\"" + trone + "\"></info>");
		}
		xml.append("</reg>");
		//log.info("reg.xml:" + xml.toString().replace("<", "&lt").replace(">", "&gt"));
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=reg.xml");
		ServletOutputStream servletOS = response.getOutputStream();
		for (int i = 0; i < xml.length(); i++) {
			servletOS.write(xml.charAt(i));
		}
		servletOS.flush();
		servletOS.close();
	}

	private int getProvinceId(String smsp) {
		if (smsp == null || "".equals(smsp)) {
			return 0;
		}
		try {
			String areaId = null;
			Cache cache = EhCacheManager.getCache();
			Element areaElement = cache.get(EhCacheManager.PROVINCE_AREA + smsp);
			if (areaElement == null) {
				areaId = provinceDao.getAreaId(smsp);
				if (areaId != null && !areaId.equals("") && !areaId.equals("0")) {
					cache.put(new Element(EhCacheManager.PROVINCE_AREA + smsp, areaId));
				}
			} else {
				areaId = (String) areaElement.getValue();
			}
			Element provinceElement = cache.get(EhCacheManager.PROVINCE_ID + areaId);
			int provinceId = 0;
			if (provinceElement == null) {
				provinceId = provinceDao.getProvinceIdByAreaId(areaId);
				if (provinceId != 0) {
					cache.put(new Element(EhCacheManager.PROVINCE_ID + areaId, provinceId));
				}
			} else {
				provinceId = (Integer) provinceElement.getValue();
			}
			return provinceId;
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}

	}
}
